package org.glut.library.dao;

import java.sql.*;
import java.util.ResourceBundle;

public class JdbcUtils {
    final static String DRIVER = getValue("jdbc.driver");
    final static String URL = getValue("jdbc.url");
    final static String USERNAME = getValue("jdbc.username");
    final static String PASSWORD = getValue("jdbc.password");

    //加载驱动程序
    static {//这样是智慧执行一次
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //创建数据库连接
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return conn;
    }

    //关闭资源
    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (stmt != null) {
                stmt.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            System.err.println("关闭数据库资源失败：" + e.getMessage());
        }
    }

    public static String getValue(String key) {
        //绑定属性文件
        ResourceBundle bundle = ResourceBundle.getBundle("database");
        return bundle.getString(key);
    }


    public static void main(String[] args) {

        System.out.println(getValue("jdbc.driver"));
        System.out.println(getValue("jdbc.url"));

        System.out.println(getConnection());
    }

}
